import xlrd
from django.forms import model_to_dict
from django.views.decorators.http import require_http_methods
from xlrd import XLRDError

from administrators.views.token_check import verify_token
from inventory.models import Material
from utils.enums import SCE
from utils.result import R


# 上传表格应该满足要求
# 物料编码 / 件 / 支 / 重量
@verify_token()
@require_http_methods(['POST'])
def in_out_table(request, user_id: int):
    try:
        file = request.FILES.get('xls_file')

        excel_type = file.name.split('.')[1]
        if excel_type not in ['xls']:
            R.error(SCE.no_enum, '上传文件的格式错误，只允许上传xls文件').data()

        data = xlrd.open_workbook(file_contents=file.read())
        table = data.sheet_by_name('Sheet1')
        rows_num = table.nrows

        result = []

        whole_piece_ = 'whole_piece'
        scatt_piece_ = 'scatt_piece'
        weight_ = 'weight'

        for row in range(rows_num):
            i = table.row_values(row, start_colx=0, end_colx=None)

            if str(i[0]).strip() == '':
                continue
            if len(i) < 4:
                return R.error(SCE.no_enum, f'第{row + 1}行数据不全，请检查').data()

            obj = model_to_dict(Material.objects.get(code=str(i[0])))

            result.append({
                'material_id': obj['id'],
                'code': obj['code'],
                'whole_piece': i[1],
                'scatt_piece': i[2],
                'model': obj['model'],
                'weight': i[3],
                'name': obj['name'],
                'remark': '',
                'now_whole_scatt_piece': f'{obj[whole_piece_]}/{obj[scatt_piece_]}',
                'now_weight': f'{obj[weight_]}'
            })
        return R.success('数据解析成功').data({'result': result, 'total': len(result)})
    except XLRDError:
        R.error(SCE.no_enum, '上传文件的格式错误，必须要有名为 Sheet1 的数据表').data()
    except Material.DoesNotExist:
        R.error(SCE.no_enum, f'第{1}行物料编码不存在，请添加该物料或纠正错误后再提交').data()
    except Exception as e:
        R.error(SCE.no_enum, f'其他故障{e}').data()


